package com.ofsoft.weixin.mp.api;

import java.io.Serializable;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;

/**
 * 请求返回
 * 
 * @author OF
 * @date 2018年07月13日
 */
public class ApiResponse implements Serializable {

	private static final long serialVersionUID = 8932491316488002897L;
	private Map<String, Object> result;
	private String json;

	public ApiResponse(String json) {
		this.json = json;
		try {
			Map<String, Object> temp = JSONObject.parseObject(json) ;
			this.result = temp;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		refreshAccessTokenIfInvalid();
	}

	private synchronized void refreshAccessTokenIfInvalid() {
		if (isAccessTokenInvalid())
			AccessTokenConfig.refreshAccessToken();
	}

	public static ApiResponse create(String json) {
		return new ApiResponse(json);
	}

	public Object get(String key) {
		return result.get(key);

	}

	public Map<String, Object> getResult() {
		return result;
	}

	public String getJson() {
		return json;
	}

	public String getStr(String name) {
		return (String) result.get(name);
	}

	public Integer getInt(String name) {
		Number number = (Number) result.get(name);
		return number == null ? null : number.intValue();
	}

	public Long getLong(String name) {
		Number number = (Number) result.get(name);
		return number == null ? null : number.longValue();
	}

	public boolean isSuccessful() {
		Integer errorCode = getErrorCode();
		return (errorCode == null || errorCode == 0);
	}

	public Integer getErrorCode() {
		return this.getInt("errcode");
	}

	public String getErrorMsg() {
		Integer errorCode = getErrorCode();
		if (errorCode != null) {
			String result = ApiErrorCode.getErrorCode(errorCode);
			if (result != null)
				return result;
		}
		return (String) result.get("errmsg");
	}

	/**
	 * 判断 API 请求结果失败是否由于 access_token 无效引起的 无效可能的情况 error_code 值： 40001 =
	 * 获取access_token时AppSecret错误，或者access_token无效(刷新后也可以引起老access_token失效)
	 * 42001 = access_token超时 42002 = refresh_token超时 40014 = 不合法的access_token
	 * 
	 * @return {boolean}
	 */
	public boolean isAccessTokenInvalid() {
		Integer ec = getErrorCode();
		return ec != null
				&& (ec == 40001 || ec == 42001 || ec == 42002 || ec == 40014);
	}

	public void set(String key, Object value) {
		result.put(key, value);
	}
}
